﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Timer = System.Windows.Forms.Timer;

namespace 实时监控电脑CPU和内存剩余量
{
    public partial class Form1 : Form
    {
        String cpucontent = "";
        String ramcontent = "";

        Timer timer; //更新界面

        //获取CPU和内存剩余
        //PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        PerformanceCounter ram = new PerformanceCounter("Memory", "Available MBytes");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += ChangeText;
            timer.Enabled = true;

            //异步实时获取
            Task.Run(() =>
            {
                while (true)
                {
                    //cpu.NextValue();
                    Thread.Sleep(1000);
                    var cpuUasage = cpu.NextValue();
                    String cpuUasagestr = String.Format("{0:f2}%", cpuUasage);

                    var ramAvailable = ram.NextValue();
                    String ramAvailablestr = String.Format("{0}MB", ramAvailable);

                    cpucontent = cpuUasagestr;
                    ramcontent = ramAvailablestr;
                }

            });

        }

        private void ChangeText(object sender, EventArgs e)
        {
            txt_cpu.Text = cpucontent;
            txt_ram.Text = ramcontent;
        }
    }
}
